package com.sjtu.service.job;

import com.sjtu.dao.repository.ClientInfoRepository;
import com.sjtu.form.JobResult;
import com.sjtu.spi.JobRunnable;
import com.sjtu.zookeeper.InstanceDetails;
import com.sjtu.zookeeper.ServiceDiscoverUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.x.discovery.ServiceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 定时刷新所有子系统的实例地址到数据库内
 * nerine
 * 2/6/2020
 */
@Slf4j
@Component("refreshClientInstance")
public class RefreshClientInstance implements JobRunnable {
    @Autowired
    private ClientInfoRepository clientInfoRepository;

    @Override
    public JobResult run() throws Exception {
        clientInfoRepository.findAll().forEach(clientInfo -> {
            ServiceProvider<InstanceDetails> provider =
                    ServiceDiscoverUtil.getServiceProvider(clientInfo.getSystemId());
            try {
                List<String> ipList = provider.getAllInstances()
                        .stream().map(e -> e.getAddress() + ":" + e.getPort())
                        .collect(Collectors.toList());
                clientInfo.setInstances(String.join(",", ipList));
                clientInfoRepository.save(clientInfo);
            } catch (Exception e) {
                log.error("error in get instance info, systemId: " + clientInfo.getSystemId(), e);
            }
        });
        return new JobResult(true, null);
    }
}
